<?php
class Zendvn_System_Auth{
    
    protected $_messageError = null;
    
    public function login($arrParam, $options = null) {
        //1. Gọi kết nối với Zend Db
        $db = Zend_Registry::get('connectDb');
        
        //2. Khởi tạo Zend Auth
        $auth = Zend_Auth::getInstance();
        
        //3. 
        $authAdapter = new Zend_Auth_Adapter_DbTable($db, $tableName, $identityColumn, $credentialColumn, $credentialTreatment);
        //$authAdapter = new Zend_Auth_Adapter_DbTable(
        //                              $zendDb, $tableName, $identityColumn, $credentialColumn, $credentialTreatment)
        $authAdapter->setTableName('users')
                    ->setIdentityColumn('user_name')
                    ->setCredentialColumn('password');
        $select = $authAdapter->getDbSelect();
        $select->where('status = 1')
               ->where(' active_code is NULL');
        
        $encode = New Zendvn_Encode();
        $user_name = $arrParam['user_name'];
        $password  = $encode->password($arrParam['password']);
        $authAdapter->setIdentity($user_name)
                    ->setCredential($password);
            
        //Lay kết quả truy vấn của Zend_Auth
        $result = $auth->authenticate($authAdapter);
        
        $flag = false;
        if(!$result->isValid()){
            $error = $result->getMessages();
            $this->_messageError = current($error);
        }else{
            //$returnColumns = array('id', 'user_name', 'email');
            //$omitColumns = array('email');
            $data = $authAdapter->getResultRowObject(null, $omitColumns);
            $auth->getStorage()->write($data);
            $flag = true;
//                $info = $auth->getIdentity();
//                echo '<br/>' . $info->user_name;
        }
        return $flag;
    }
    
    public function getError() {
        return $this->_messageError;
    }
    
    public function logout($arrParam = null, $options = null) {
        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
    }
}
